/*
 * Created by 岱青海蓝信息系统(北京)有限公司 on 17-6-16 上午11:16
 * Copyright (c) 2017. All rights reserved.
 */

package com.example.dqhl.jdmetro.fragment.Consulation;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;

import com.example.dqhl.jdmetro.R;
import com.example.dqhl.jdmetro.activities.ConsulationDeatilActivity;
import com.example.dqhl.jdmetro.adapter.consulation.ConsulationDataAdapter;
import com.example.dqhl.jdmetro.base.BaseFragment;
import com.example.dqhl.jdmetro.bean.User;
import com.example.dqhl.jdmetro.bean.consulation.ConsulationData;
import com.example.dqhl.jdmetro.config.Config;
import com.example.dqhl.jdmetro.config.Constant;
import com.example.dqhl.jdmetro.utils.Dlog;
import com.example.dqhl.jdmetro.utils.JsonUtils;
import com.example.dqhl.jdmetro.utils.JumpItent;
import com.example.dqhl.jdmetro.utils.Toastutils;
import com.example.dqhl.jdmetro.view.swipyrefreshlayout.SwipyRefreshLayout;
import com.example.dqhl.jdmetro.view.swipyrefreshlayout.SwipyRefreshLayoutDirection;
import com.google.gson.Gson;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.lcodecore.tkrefreshlayout.header.progresslayout.ProgressLayout;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * description:资讯  公共Fragment
 * autour:guanluocang
 * date:17/6/16 11:17
 */
public class ConsultationCommonFragment extends BaseFragment implements SwipyRefreshLayout.OnRefreshListener {

    @Bind(R.id.consulaton_commen_refresh_layout)
    TwinklingRefreshLayout consulaton_commen_refresh_layout;
    private Context context;
    //    @Bind(R.id.refreshLayout)
//    SwipyRefreshLayout refreshLayout;
    @Bind(R.id.recycleView)
    RecyclerView recycleView;
    private String theme_id = "";//主题ID

    private List<ConsulationData.DataBean> consulationDataList = new ArrayList<>();
    private List<ConsulationData.DataBean.PicAllBean> pic_allList = new ArrayList<>();
    private ConsulationDataAdapter consulationDataAdapter;
    private int page = 1;

    @Override
    public View initView(LayoutInflater inflater) {
        rootView = inflater.inflate(R.layout.fragment_consultation_common, null);
        ButterKnife.bind(this, rootView);
        context = getActivity();
        registerBroadcastReceiver();
        theme_id = getArguments().getString("theme_id");
        Dlog.e(theme_id + "flag");
        LinearLayoutManager linearLayoutManager_list = new LinearLayoutManager(getActivity());
        linearLayoutManager_list.setOrientation(LinearLayoutManager.VERTICAL);
        recycleView.setLayoutManager(linearLayoutManager_list);
        recycleView.addItemDecoration(new DividerItemDecoration(context, DividerItemDecoration.VERTICAL));


        return rootView;
    }

    @Override
    public void initData() {
        consulationDataAdapter = new ConsulationDataAdapter(context);
        recycleView.setAdapter(consulationDataAdapter);
        ProgressLayout headerView = new ProgressLayout(getActivity());
        consulaton_commen_refresh_layout.setHeaderView(headerView);
        consulaton_commen_refresh_layout.setOverScrollRefreshShow(false);
        doData(page);

    }

    @Override
    public void initListener() {
        consulaton_commen_refresh_layout.setOnRefreshListener(new RefreshListenerAdapter() {
            @Override
            public void onRefresh(final TwinklingRefreshLayout refreshLayout) {
                page = 1;
                doData(page);
                refreshLayout.finishRefreshing();
            }

            @Override
            public void onLoadMore(final TwinklingRefreshLayout refreshLayout) {
                page++;
                loadMoreList(page);
                refreshLayout.finishLoadmore();
            }
        });
    }

    /**
     *
     * 获取列表
     * */
    public void doData(int pages){
        showLoadingBar("");
        RequestParams params = new RequestParams(Config.consulation_other_data);
        params.addBodyParameter("theme_id", theme_id);
        params.addBodyParameter("page", pages + "");
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Dlog.e("政策解读其他专栏" + result);
                int errCode = JsonUtils.getErrCode(result);
                String errMsg = JsonUtils.getErrMsg(result);
                String data = JsonUtils.getData(result);
                if (errCode == 200) {

                    ConsulationData consulationData = new Gson().fromJson(result, ConsulationData.class);
                    consulationDataList = consulationData.getData();
//                    rv_consulationList.setAdapter(consulationDataAdapter = new ConsulationDataAdapter(context, consulationDataList));
                    consulationDataAdapter.refresh_list(consulationDataList);
                    consulationDataAdapter.setOnItemClickListener(new ConsulationDataAdapter.onItemClickListener() {
                        @Override
                        public void onItemClick(View view, int position) {
                            if (user != null) {
                                Bundle bundle = new Bundle();
                                bundle.putString("info_id", consulationDataList.get(position).getInfo_id());
                                JumpItent.jump(getActivity(), ConsulationDeatilActivity.class, bundle);
                            } else {
                                Toastutils.show("请先登录");
                            }

                        }
                    });
                } else {
                    Toastutils.show(errMsg);
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                hideLoadingBar();
            }
        });
    }

    /**
     *
     * 加载更多
     * */
    public void loadMoreList(int pages){
        showLoadingBar("");
        RequestParams params = new RequestParams(Config.consulation_other_data);
        params.addBodyParameter("theme_id", theme_id);
        params.addBodyParameter("page", pages + "");
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Dlog.e("政策解读其他专栏" + result);
                int errCode = JsonUtils.getErrCode(result);
                String errMsg = JsonUtils.getErrMsg(result);
                String data = JsonUtils.getData(result);
                if (errCode == 200) {

                    ConsulationData consulationData = new Gson().fromJson(result, ConsulationData.class);
                    consulationDataList.addAll(consulationData.getData());
                    consulationDataAdapter.refresh_list(consulationDataList);
                } else {
                    Toastutils.show(errMsg);
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                hideLoadingBar();
            }
        });
    }

    /**
     * 广播接收者
     */
    BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(Constant.ACTION_LOGIN_SUCCESS)) {
                user = (User) intent.getExtras().get("user");
                Dlog.e(user.toString());
            } else if (action.equals(Constant.ACTION_LOGOUT_SUCCESS)) {
                user = null;
            }
        }
    };

    /**
     * 注册广播接收者
     */
    private void registerBroadcastReceiver() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Constant.ACTION_LOGIN_SUCCESS);
        intentFilter.addAction(Constant.ACTION_LOGOUT_SUCCESS);
        context.registerReceiver(receiver, intentFilter);
    }
    /**
     * 下拉刷新的操作
     */
    @Override
    public void onRefresh(SwipyRefreshLayoutDirection direction) {

    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        ButterKnife.unbind(this);
        if (receiver != null) {
            context.unregisterReceiver(receiver);
        }
    }
}
